<?php
/**
 * AJAX Handler for Rating a project - Adds a rating to the project (or fails if constraints are unmet, such as user has already rated).
 * NOTE: HTTP/1.1 403 Forbidden - if guest user attempts.
 * 
 * I have made sure Libdebug is silent in AJAX. This is because it can intefere with the HTML/Javascript as Libdebug Appends after </html>.
 * If you have a problem and need to debug comment $_LIBDEBUG->silence(); (the framework must also be in debugging mode for this to work)
 */

    $_ECLIPSEMDE = array();
    
    // Disable Templating System
    $_ECLIPSEMDE['TEMPLATING'] = false;
    require_once('../../SiteIncludes.GLOBAL.php');
    
    // Tell libdebug to never print out error information - overrides debugging flags in fwork
    $_LIBDEBUG->silence();
    
    // Not Authenticated to rate
    if(isset($_LOGGEDINUSER) === false || (isset($_LOGGEDINUSER) === true && $_LOGGEDINUSER === false)) {
	header("HTTP/1.1 403 Forbidden");
	die('-1');
    }
    
    // Incorrect Input
    if(isset($gVAR['tool'])) {
	try {
	    $Project =& $ProjectStash->get($gVAR['tool']);
	} catch(Exception $e) {
	    header("HTTP/1.1 400 Bad Request");
	    die('-1');
	}
    }
    if(isset($gVAR['val'])) {
	if($gVAR['val'] < 0 || $gVAR['val'] > 5) {
	    header("HTTP/1.1 400 Bad Request");
	    die('-1');
	}
    }
    
    // Ensure All Variables Are Set
    // Ensure User is valid and logged in
    if(isset($gVAR['tool']) === true && isset($gVAR['val']) === true && isset($_LOGGEDINUSER) === true && $_LOGGEDINUSER !== false) {
	$Project =& $ProjectStash->get($gVAR['tool']);
	$value = ((int)$gVAR['val']);
	$userid = $_LOGGEDINUSER->get_userid();
	$hasRated = $Project->hasUserRated($userid);
	    // Check Value is valid
	if($hasRated === false) {
	    $Project->addRating((int)$userid, $value);
	    header("HTTP/1.1 200 OK");
	    
	    echo <<<EOR
		<!DOCTYPE html>
		    <html>
			<head>
			    <title>Rate</title>
			</head>
			<body>
			    <script type="text/javascript">
				parent.ratingUpdate('{$Project->getAverageRating()}');
			    </script>
			</body>
		    </html>
EOR;
	    
	    ob_flush();
	    die();
	}
    }
    
    header("HTTP/1.1 400 Bad Request");
    die('-1');
    
?>
